package com.idol.dao.impl;

import com.idol.annotation.Autowired;
import com.idol.dao.AccountDao;
import com.idol.pojo.Account;
import com.idol.util.ConnectionUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * @author Supreme_Sir
 * @version 1.0
 * @className AccountDaoImpl
 * @description
 * @date 2020/10/13 10:33
 **/
public class AccountDaoImpl implements AccountDao {
    @Autowired
    private ConnectionUtil connectionUtil;

    public ConnectionUtil getConnectionUtil() {
        return connectionUtil;
    }

    @Override
    public Account queryAccountByCardNo(String cardNo) throws Exception {
        Connection connection = connectionUtil.getCurrentThreadConn();
        String sql = "select `name`, money, cardNo from `account` where cardNo=?";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setObject(1, cardNo);
        ResultSet resultSet = preparedStatement.executeQuery();

        Account account = new Account();
        while (resultSet.next()) {
            account.setName(resultSet.getString("name"));
            account.setMoney(resultSet.getInt("money"));
            account.setCardNo(resultSet.getString("cardNo"));
        }

        resultSet.close();
        preparedStatement.close();

        return account;
    }

    @Override
    public int updateAccountByCardNo(Account account) throws Exception {
        Connection connection = connectionUtil.getCurrentThreadConn();
        String sql = "update `account` set money=? where cardNo=?";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setObject(1, account.getMoney());
        preparedStatement.setObject(2, account.getCardNo());
        int row = preparedStatement.executeUpdate();
        preparedStatement.close();
        return row;
    }
}
